package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2VO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private  CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //首先找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
             categoryEntity.getParentCid() == 0
        ).map((menu) ->{
            menu.setChildren(getChildren(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null ?0:menu1.getSort()) - (menu2.getSort()==null ?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenusByIds(List<Long> ids) {
        //TODO 删除的时候检查是否被别的地方引用
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> categoryPath = findCategoryPath(catelogId, paths);
        Collections.reverse(categoryPath);
        return paths.toArray(new Long[categoryPath.size()]);
    }

    @CacheEvict(value = "category" , allEntries = true)//将缓存进行清空
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(CategoryEntity category) {
        //首先将自己的信息进行修改
        this.updateById(category);
        //当分类信息进行修改的时候也要将冗余的字段进行修改
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }

    @Override
    @Cacheable(value = {"category"} ,key = "#root.method.name") //代表该方法需要缓存，如果缓存中有，方法不会调用。如果没有则会调用方法，将结果放入缓存
    public List<CategoryEntity> getLevel1Categorys() {
        LambdaQueryWrapper<CategoryEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CategoryEntity::getCatLevel,1);
        lambdaQueryWrapper.last("limit 16");
        List<CategoryEntity> list = this.list(lambdaQueryWrapper);
        return list;
    }

    @Cacheable(value = {"category"} ,key = "#root.method.name")
    @Override
    public Map<String, List<Catelog2VO>> getCatelogJson() {
        //查询所有一级分类
        List<CategoryEntity> level1Categorys = this.getLevel1Categorys();
        //封装数据
        Map<String, List<Catelog2VO>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询每一个一级分类的二级分类
            List<CategoryEntity> categoryEntityList = baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, v.getCatId()));
            //封装上面的结果
            List<Catelog2VO> catelog2VOS = null;
            if (!ObjectUtils.isEmpty(categoryEntityList)) {
                catelog2VOS = categoryEntityList.stream().map(l2 -> {
                    Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = baseMapper.selectList(new LambdaQueryWrapper<CategoryEntity>().eq(CategoryEntity::getParentCid, l2.getCatId()));
                    if(!ObjectUtils.isEmpty(level3Catelog)){
                        List<Catelog2VO.Catelog3VO> catelog3VOS = level3Catelog.stream().map(l3 -> {
                            Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l2.getCatId().toString(),l3.getCatId().toString(),l3.getName());
                            return catelog3VO;
                        }).collect(Collectors.toList());
                        catelog2VO.setCatalog3List(catelog3VOS);
                    }
                    return catelog2VO;
                }).collect(Collectors.toList());
            }
            return catelog2VOS;
        }));
        return parent_cid;
    }


    //根据分类id查询父亲id的全路径
    private List<Long> findCategoryPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        //首先查询出来当前分类的详情
        CategoryEntity category = baseMapper.selectById(catelogId);
        if (category.getParentCid() != 0){
            findCategoryPath(category.getParentCid(),paths);
        }
        return paths;
    }


    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all) {
        //递归找到所有子菜单
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> {
            //找到子菜单
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null ?0:menu1.getSort()) - (menu2.getSort()==null ?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }
}